// 导入axios
import axios from 'axios'
import router from '@/router'
import { Notification } from 'element-ui'
// import { getXmStorage } from '@/utils'
 
// 基地址
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 20000
})
 
// 请求拦截
service.interceptors.request.use(
  config => {
    // const token = getXmStorage('token')
    // if (token) {
    //   config.headers['Authorization'] = `Bearer ${token}`
    // }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
 
service.interceptors.response.use(response => {
  if (response.data.status === 401) { // token过期
    Notification.error({
      title: '很抱歉，登录已过期，请重新登录',
      duration: 5000
    })
    localStorage.removeItem('token')
    router.push(`/login`)
    return Promise.reject()
  } else {
    return response.data
  }
}, error => {
  var code = 0
  try {
    code = error.response.data.status
  } catch (err) {
    if (error.toString().indexOf('timeout') > -1) {
      Notification.error({
        title: '网络请求超时',
        duration: 4000
      })
      return Promise.reject(error)
    }
  }
  if (code) {
    if (code === 401) {
      Notification.error({
        title: '很抱歉，登录已过期，请重新登录',
        duration: 5000
      })
      localStorage.removeItem('token')
      router.push(`/login`)
    } else if (code === 404) {
      Notification.error({
        title: '很抱歉，资源未找到!',
        duration: 4000
      })
    } else {
      const errorMsg = error.response.data.message
      if (errorMsg !== undefined) {
        Notification.error({
          title: errorMsg,
          duration: 4000
        })
      }
    }
  } else {
    Notification.error({
      title: '系统升级中，请稍后再试！',
      duration: 4000
    })
  }
  return Promise.reject(error)
})

 
// 暴露副本
export default service